using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Project;
using Microsoft.WowAddonStudio.Project;

namespace Microsoft.WowAddonStudio.TocEditor
{
	[ComVisible(true)]
	[Guid(GuidStrings.TocEditorFilesPage)]
	public class TocEditorFilesPage : SettingsPage
	{
		private FileListManager manager;

		/// <summary>
		/// Initializes a new instance of the <see cref="TocEditorFilesPage"/> class.
		/// </summary>
		public TocEditorFilesPage()
		{
			Name = Resources.GetString(Resources.FileListCaption);
		}

		/// <summary>
		/// Activates the specified parent.
		/// </summary>
		/// <param name="parent">The parent.</param>
		/// <param name="pRect">The p rect.</param>
		/// <param name="bModal">The b modal.</param>
		public override void Activate(IntPtr parent, RECT[] pRect, int bModal)
		{
			base.Activate(parent, pRect, bModal);

			if (ProjectMgr is WowProjectNode)
			{
				var mgr = ProjectMgr as WowProjectNode;
				manager = new FileListManager(mgr.TocDocument,
				                              mgr.GetRelativeFilePathsWithoutToc());
				manager.OnFileListChanged += manager_OnFileListChanged;
				var fs = new FileListSelectorControl(manager);
				base.ThePanel.Controls.Add(fs);
			}
			else
			{
				throw new ApplicationException("Project manager type incompatibility error.");
			}
		}

		/// <summary>
		/// Deactivates this instance.
		/// </summary>
		public override void Deactivate()
		{
			base.Deactivate();
            if (manager != null)
			    manager.OnFileListChanged -= manager_OnFileListChanged;
		}

		/// <summary>
		/// Handles the OnFileListChanged event of the manager control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="Microsoft.WowAddonStudio.TocEditor.FileListManagerEventArgs"/> instance containing the event data.</param>
		private void manager_OnFileListChanged(object sender, FileListManagerEventArgs e)
		{
			IsDirty = true;
		}

		/// <summary>
		/// Applies the changes.
		/// </summary>
		/// <returns></returns>
		protected override int ApplyChanges()
		{
			if (ProjectMgr is WowProjectNode)
			{
				if (IsDirty)
				{
					var mgr = ProjectMgr as WowProjectNode;
					mgr.TocDocument.Files.Clear();

					foreach (var file in manager.Files)
					{
						if (file.IsIncluded)
							mgr.TocDocument.Files.Add(file.RelativePath);
					}

					mgr.SaveTocDocument();
					IsDirty = false;
				}

				return VSConstants.S_OK;
			}

			return VSConstants.E_INVALIDARG;
		}

		/// <summary>
		/// Binds the properties.
		/// </summary>
		protected override void BindProperties()
		{
		}
	}
}